package com.hzw.saas.common.config.configuration;

import javax.annotation.Resource;

import com.hzw.saas.common.config.annotation.SysLog;
import com.hzw.saas.common.config.constants.RedisConsts;
import com.hzw.saas.common.config.util.RedisUtil;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 *
 * </p>
 *
 * @author sonam
 * @since 2021/4/6 17:43
 */
@Slf4j
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Resource
    private ApplicationEventPublisher eventPublisher;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void init() {
        setKeyspaceNotificationsConfigParameter(null);
        super.init();
    }

    @SysLog(operation = "key过期事件", mode = 1)
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String key = message.toString();
        if (key.startsWith(RedisConsts.GROUP_LISTEN_EXPIRE_TRIGGER)) {
            String tKey = RedisConsts.GROUP_LISTEN_EXPIRE_EVENT + key.substring(RedisConsts.GROUP_LISTEN_EXPIRE_TRIGGER.length());
            log.debug("listening key {} expired", tKey);
            Object o = RedisUtil.get(tKey);
            if (RedisUtil.hasKey(tKey))
                RedisUtil.del(tKey);
            if (o != null)
                eventPublisher.publishEvent(o);
        }
    }

}
